<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <a href="#/home">首页</a>
  <a href="#/about">关于</a>

  <div id="app"></div>


  <script>
    const routes = [
      {
        path: "/home",
        component: () => {
          return "首页页面"
        }
      },
      {
        path: "/about",
        component: () => {
          return "关于页面"
        }
      }
    ]
    const app = document.getElementById("app");
    window.addEventListener("hashchange", () => {
      const localhash = window.location.hash;
      console.log(localhash);
      routerView(localhash)
    })

    window.addEventListener("DOMContentLoaded", () => {
      routerView(location.hash)
    })

    function routerView(localhash) {
      // 去 routes 数组中查找 localhash 值在哪一项中
      // 找到了就返回这一项中的 component 执行结果放进 app 中
      const index = routes.findIndex((item) => {
        return '#' + item.path === localhash
      })
      const content = routes[index].component()
      app.innerHTML = content
    }
  </script>
</body>

</html>